package com.apps.MiniChat;


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ChatRoom extends MapActivity  implements OnClickListener , LocationListener{


	//Communication
	private Socket socket = null;
	private ServerSocket serverSocket= null;
	private String serverIpAddress = "";
	private int serverPort = 6000;
	private TextView ip;
	private TextView serverStatus;
	private String mClientMsg = "";
	private boolean server;
	private ObjectInputStream inputStream = null;
	private ObjectOutputStream outputStream = null;
	private boolean objectTreat = true;
	
	//Thread de communication
	private Thread communicationReadThread = null;
	private Thread communicationWriteThread = null;
	
	//Layout
	private RelativeLayout serverLayout;
	private RelativeLayout chatLayout;
	private RelativeLayout userNameLayout;
	private RelativeLayout photoLayout;
	
	//Chat
	private EditText chatNonEditText;
	private EditText sendEditText;
	private Button sendTextButton;
	private boolean firstText = true;

	//Object Send et Receive
	private SendObject sendObject;
	private SendObject receiveObject;
	private boolean readySend = false;
	
	//Name Chat
	private String hisName = "";
	private String myName = "";
	
	//Map Location
	private LocationManager locationManager;
	private Geocoder geocoder;
	private MapView map;  
	private MapController mapController;
	private GeoPoint pointReceive;
	private int[] geoPoint = new int[2];
	private boolean locationOn = true;
	private Button locationButton;
	private CheckBox locationCheckBox;
	private TextView locationTextview;
	private SendObject sendObjectLocation;
	private boolean readySendLocation = false;
	
	//Photo 
	private Intent intent;
	private Bitmap bmp;
	private int cameraData;
	private BitmapDataObject bmpObject;
	private BitmapDataObject bmpObjectRead;
	private ByteArrayOutputStream stream;
	private ImageButton sendPhotoButton;
	private ImageButton gallaryButton;
	
	
	//Sound
	private static String mFileName;
	private static String mFileNameReceive;
	private boolean recording = false;
	private MediaRecorder mRecorder;
	private MediaPlayer   mPlayer;
	private File file;
    private byte [] soundByte;
	private ImageButton sendVoiceImageButton;
	private ImageButton playStopImageButton;
	private boolean playing = false;
    
    //Layout Username
    private EditText userName;
    private Button sendUser;
    private boolean nameReceive = false;
    private boolean nameSend = false;
    
    //Button SignOut
    private Button signOutButton;
    
    //Layout Photo
    private ImageView image;
    private ImageButton closeButton;
    
    //Handler
    protected static final int MSG_ID = 0x1337;
	protected static final int MSG_START = 0x1338;
	protected static final int MSG_EDIT_TEXT = 0x1339;
	protected static final int MSG_LOCATION = 0x1340;
	protected static final int MSG_PHOTO = 0x1341;
	protected static final int MSG_SOUND = 0x1342;
	protected static final int MSG_USER = 0x1343;
	protected static final int MSG_CLOSE = 0x1344;
	protected static final int MSG_LOCATION_STATUS = 0x1345;
	protected static final String TEXT = "Text";
	protected static final String LOCATION = "Location";
	protected static final String PHOTO = "Photo";
	protected static final String SOUND = "Sound";
	protected static final String USER = "UserName";
	protected static final String CLOSE = "Close";
	protected static final String LOCATION_STATUS = "LocationStatus";
	protected static final String ON = "ON";
	protected static final String OFF = "OFF";
	

	//Draw le marker
	class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
            super.draw(canvas, mapView, shadow);                   
 
            //GeoPoint to Point
            Point screenPts = new Point();
            mapView.getProjection().toPixels(pointReceive, screenPts);
 
            //add la fleche (marker)
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.marker);            
            canvas.drawBitmap(bmp, screenPts.x+15, screenPts.y-50, null);         
            return true;
        }
    } 
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	    setContentView(R.layout.chat);
	    
	    //Layout Server
	    serverLayout = (RelativeLayout) findViewById(R.id.relativeLayout1);
	    ip = (TextView) findViewById(R.id.serverText);
        serverStatus = (TextView) findViewById(R.id.serverStatusText);
	    
        //Layout Chat
        chatLayout = (RelativeLayout) findViewById(R.id.relativeLayout2);
        chatNonEditText = (EditText) findViewById(R.id.chatNonEditText);
        sendEditText = (EditText) findViewById(R.id.sendEditText);
        sendTextButton = (Button) findViewById(R.id.sendTextButton);
        sendTextButton.setOnClickListener(this);
        map = (MapView) findViewById(R.id.mapView);
        sendVoiceImageButton =(ImageButton) findViewById(R.id.sendVoiceImageButton);
        sendVoiceImageButton.setOnClickListener(this);     
        playStopImageButton = (ImageButton) findViewById(R.id.playStopImageButton);
        playStopImageButton.setOnClickListener(this); 
        sendPhotoButton = (ImageButton) findViewById(R.id.sendPhotoImageButton);
        sendPhotoButton.setOnClickListener(this);
        signOutButton = (Button) findViewById(R.id.signOutButton);
        signOutButton.setOnClickListener(this);
        gallaryButton = (ImageButton) findViewById(R.id.galleryImageButton);
        gallaryButton.setOnClickListener(this);
        locationTextview = (TextView) findViewById(R.id.locationTextView);
        sendObject  = new SendObject();
        receiveObject = new SendObject();
        sendObjectLocation = new SendObject();
  
        chatNonEditText.setFocusable(false);
        
        //Layout UserName
        userNameLayout = (RelativeLayout) findViewById(R.id.relativeLayoutName);
        userName = (EditText) findViewById(R.id.userNameEditText);
        sendUser = (Button) findViewById(R.id.sendUser);
        sendUser.setOnClickListener(this);
        locationCheckBox = (CheckBox) findViewById(R.id.enableLocationCheckBox);
        
        //Map
        locationButton = (Button) findViewById(R.id.disableLocationButton);
        locationButton.setOnClickListener(this);
        map.setBuiltInZoomControls(true); 
        mapController = map.getController(); 
        mapController.setZoom(16);
        locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
        geocoder = new Geocoder(this); 
        
        //Image
        stream = new ByteArrayOutputStream();
        
        //Sound nom des fichiers
        mFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/audioRecord.3gp";
        mFileNameReceive = Environment.getExternalStorageDirectory().getAbsolutePath() + "/audioPlay.3gp";
        
        //Layout Photo
        photoLayout = (RelativeLayout) findViewById(R.id.photoRelativeLayout);
        image = (ImageView) findViewById (R.id.photoReceive);
        closeButton = (ImageButton) findViewById (R.id.closeImageButton);
        closeButton.setOnClickListener(this);
        
        //Debut du chat
	    initChat();
	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			if(server && serverSocket!= null)
				serverSocket.close();
			if(socket != null)
				socket.close();
        	if(inputStream != null)
        		inputStream.close();
        	if(outputStream != null)
        		outputStream.close();
        	stream.close();
        	if (playing)
        		stopAudio();
        	
        } catch (IOException e) {
                e.printStackTrace();
        }
	}

	
	 @Override
	 protected void onResume() {
      super.onResume();
      //Resume de chercher la localisation
      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER , 60000, 10, this); 
    }

    @Override
    protected void onPause() {
      super.onPause();
      locationManager.removeUpdates(this); 
    }

	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		//Pour le texte
		if (v.getId() == R.id.sendTextButton)
		{
			sendObject.setType(TEXT);
			sendObject.setObject(sendEditText.getText().toString());
			readySend = true;
			
			//Ajoute un Enter a la premiere ligne de texte
			if (!firstText)
        	{
        		chatNonEditText.append("\n");
        	}
        	else
        		firstText = false;
        	
        	chatNonEditText.append(myName + ": ");
			chatNonEditText.append(sendEditText.getText().toString());
			
			sendEditText.clearFocus();
			sendEditText.setText("");
		}
		//Pour la bouton localisation
		else if(v.getId()== R.id.disableLocationButton)
		{
			if (locationOn)
			{
				disableLocation();
			}
			else
			{
				enableLocation();
			}
			locationOn = !locationOn;
				
		}
		//Pour la Photo
		else if (v.getId()== R.id.sendPhotoImageButton)
		{
			intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent,cameraData);
		}
		//Pour la voix
		else if(v.getId() == R.id.sendVoiceImageButton)
		{
			if(!recording)
			{
				sendVoiceImageButton.setImageResource(R.drawable.stop);
				mRecorder = new MediaRecorder();
		        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		        
		        mRecorder.setOutputFile(mFileName);
		        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		        try {
		            mRecorder.prepare();
		        } catch (IOException e) {
		            Log.e("Record", "prepare() failed");
		        }

		        mRecorder.start();
			}
			else
			{
				sendVoiceImageButton.setImageResource(R.drawable.micro);
				mRecorder.stop();
		        mRecorder.release();
		        mRecorder = null;
		        
		        sendObject.setType(SOUND);
		        file = new File(mFileName);
		        soundByte = new byte[(int)file.length()];
				try {
					FileInputStream fileInput = new FileInputStream(file);
					BufferedInputStream bufferedInput = new BufferedInputStream(fileInput);
					bufferedInput.read(soundByte,0,soundByte.length);
					fileInput.close();
					bufferedInput.close();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				sendObject.setObject(soundByte);
				readySend = true;
			}		
			recording = !recording;
		}
		//Pour le nom de l'utilisateur et la localisation
		else if(v.getId() == R.id.sendUser)
		{
			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(userName.getWindowToken(), 0);

			myName = userName.getText().toString();
			sendObject.setType(USER);
			sendObject.setObject(myName);
			readySend = true;
			nameSend = true;
			
			if(!locationCheckBox.isChecked())
			{
				disableLocation();
			}
			else
			{
				enableLocation();
			}
			
			if (!nameReceive)
			{
				userNameLayout.setVisibility(View.GONE);
				serverLayout.setVisibility(View.VISIBLE);
				ip.setText("Waiting for other user ...");
	    		serverStatus.setText("");
			}
			else
			{
				userNameLayout.setVisibility(View.GONE);
				chatLayout.setVisibility(View.VISIBLE);
			}	
				
		}
		//Pour jouer ou arreter la voix
		else if (v.getId() ==  R.id.playStopImageButton)
		{
			if (!playing)
			{
				playAudio();
			}
			else 
			{
				stopAudio();
			}
			playing = !playing;
		}
		//Pour sign Out
		else if (v.getId() == R.id.signOutButton)
		{
			//Send a l'autre de fermer.
			sendObject.setType(CLOSE);
			readySend = true;	
			finish();
		}
		//Pour fermer la vue de la photo
		else if (v.getId() == R.id.closeImageButton)
		{
			//Ferme la view
			photoLayout.setVisibility(View.GONE);
			chatLayout.setVisibility(View.VISIBLE);
		}
		//Pour ouvrir la vu de photo
		else if (v.getId() == R.id.galleryImageButton)
		{
			chatLayout.setVisibility(View.GONE);
			serverLayout.setVisibility(View.GONE);
			userNameLayout.setVisibility(View.GONE);
        	photoLayout.setVisibility(View.VISIBLE);
		}
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//recoit l'image retourne par l'activite
		if (resultCode == RESULT_OK)
		{
			Bundle extras = data.getExtras();
			bmp = (Bitmap) extras.get("data");
			
		    bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
		    bmpObject = new BitmapDataObject();
		    bmpObject.setImageByteArray(stream.toByteArray());
		    stream.reset();

		    
		    sendObject.setType(PHOTO);
			sendObject.setObject(bmpObject);
			readySend = true;
			
		}
	}
	
	//Initie le Chat
	private void initChat()
	{
		playStopImageButton.setVisibility(ImageButton.GONE); 
		gallaryButton.setVisibility(ImageButton.GONE);
		photoLayout.setVisibility(View.GONE);
		chatLayout.setVisibility(View.GONE);
		userNameLayout.setVisibility(View.GONE);
		serverLayout.setVisibility(View.VISIBLE);
		
        Bundle extras = getIntent().getExtras();
        if (extras !=null)
        {
        	
        	if (extras.getBoolean("Server"))
        	{
        		serverIpAddress = extras.getString("IP");
        		serverPort = MenuChat.Port;
        		ip.setText("The IP of the Server is: " + serverIpAddress + " Port: " + serverPort);
        		serverStatus.setText("Waiting for client to connect...");
        		Thread cThread = new Thread(new ServerConnectThread());
                cThread.start();
                server = true;
        	}
        	else
        	{
        		serverLayout.setVisibility(View.GONE);
        		serverIpAddress = extras.getString("IP");
        		serverPort = extras.getInt("PORT");
        		Thread cThread = new Thread(new ClientConnectThread());
                cThread.start();
                server = false;
        	}
        }
	}
	
	//Pour debuter le Chat apres avoir reussi la connexion
	private void startChat()
	{
		communicationReadThread= new Thread(new CommunicationRead());
		communicationWriteThread = new Thread (new CommunicationWrite());
		communicationReadThread.start();
		communicationWriteThread.start();
		userNameLayout.setVisibility(View.VISIBLE);
		serverLayout.setVisibility(View.GONE);
	}
	
	
	//Le handler
	Handler myUpdateHandler = new Handler() {
        public void handleMessage(Message msg) {
                switch (msg.what) {
                //Pour le serveur quand la connexion est etablie
                case MSG_ID:
                        TextView tv = (TextView) findViewById(R.id.serverStatusText);
                        tv.setText(mClientMsg);
                        serverLayout.setVisibility(View.GONE);
                        
                        //Start to Chat
                        startChat();
                        objectTreat = true;
                        break;
                 //Pour le client quand la connexion est etablie
                case MSG_START:
                	startChat();
                	objectTreat = true;
                	break;
                	//Lorsqu'on recoit un Text
                case MSG_EDIT_TEXT:
                	if (!firstText)
                	{
                		chatNonEditText.append("\n");
                	}
                	else
                		firstText = false;
                	
                	chatNonEditText.append( hisName + ": ");
                	chatNonEditText.append(receiveObject.getObject().toString());
                	objectTreat = true;
                	break;
                	//Lorsqu'on recoit la localisation
                case MSG_LOCATION:
                	
                	int[] point = (int[]) receiveObject.getObject();
                	pointReceive = new GeoPoint(point[0],point[1]);
                	mapController.animateTo(pointReceive); 

                	//Location Marker
                	MapOverlay mapOverlay = new MapOverlay();
                	List<Overlay> listOfOverlays = map.getOverlays();
                	listOfOverlays.clear();
   			    	listOfOverlays.add(mapOverlay); 
   			    	objectTreat = true;
                	break;
                	
                	//Lorsqu'on recoit une photo
                case MSG_PHOTO:
            	
                	//Set chat Layout Gone and photo visible
                	chatLayout.setVisibility(View.GONE);
        			serverLayout.setVisibility(View.GONE);
        			userNameLayout.setVisibility(View.GONE);
                	photoLayout.setVisibility(View.VISIBLE);
                	gallaryButton.setVisibility(ImageButton.VISIBLE);
                	
                	bmpObjectRead = (BitmapDataObject)receiveObject.getObject();
                	Bitmap bmpReceive = BitmapFactory.decodeByteArray(bmpObjectRead.getImageByteArray(),
                             0, bmpObjectRead.getImageByteArray().length);        	
                	image.setImageBitmap(bmpReceive);
                	objectTreat = true;
                	break;
                	//Lorsqu'on recoit un son
                case MSG_SOUND:
                	
                	if (playing)
                	{
                		stopAudio();
                	}
                	
                	//Create the file
                	File myFile = new File(mFileNameReceive);   
                	
                	try {
						myFile.createNewFile();
						FileOutputStream fOut = new FileOutputStream(myFile);
						fOut.write((byte[]) receiveObject.getObject());
						fOut.close();
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
                	
                	playAudio();
                	
                	if (playStopImageButton.getVisibility() == ImageButton.GONE)
                	{
                		playStopImageButton.setVisibility(ImageButton.VISIBLE);
                	}
                	objectTreat = true;
                	break;
                	
                	//Lorsqu'on recoit le nom de l'usager
                case MSG_USER:
                	hisName = (String) receiveObject.getObject();
                	locationTextview.setText(hisName + " disabled Location");
                	nameReceive = true;
                	if (nameSend)
                	{
                		chatLayout.setVisibility(View.VISIBLE);
                    	userNameLayout.setVisibility(View.GONE);
                	}
                	objectTreat = true;
                	break;
                	//Lorsqu'on recoit Signout
                case MSG_CLOSE:
                	finish();
                	break;
                	//Lorsqu'on recoit le status de la localisation
                case MSG_LOCATION_STATUS:
                	if (receiveObject.getObject().toString().equals(ON))
                	{
                		map.setVisibility(View.VISIBLE);
                		locationTextview.setVisibility(TextView.GONE);
                	}
                	else 
                	{
                		locationTextview.setText(hisName + " disabled Location");
                		map.setVisibility(View.GONE);
                		locationTextview.setVisibility(TextView.VISIBLE);
                	}
                	objectTreat = true;
                	break;
                default:
                        break;
                }
                super.handleMessage(msg);
        }
	};
	
	//Thread to connect for the Server
		class ServerConnectThread implements Runnable {
	        public void run() {                
	            try {
	            	serverSocket = new ServerSocket(serverPort);

	            	Log.d("GameScreen", "Server: Avant Accept");
	            	if (socket == null)
	                    socket = serverSocket.accept();
	            	socket.setKeepAlive(true);
	            	outputStream = new ObjectOutputStream(socket.getOutputStream());
	            	outputStream.flush();
	            	inputStream = new ObjectInputStream(socket.getInputStream());

	            	 Message m = new Message();
	                 m.what = MSG_ID;
	                 mClientMsg = "Connected";
	                 myUpdateHandler.sendMessage(m);
	            	
	            } catch (IOException e) {
	                    e.printStackTrace();
	            }
	        }
	    }
		//Thread to connect for the Client
		class ClientConnectThread implements Runnable {
	        public void run() {                
	            try {
	            	
	            	Log.d("GameScreen", "Client before connected");
	            	InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
	            	socket = new Socket(serverAddr, serverPort);
	            	socket.setKeepAlive(true);
	            	outputStream = new ObjectOutputStream(socket.getOutputStream());
	            	outputStream.flush();
	            	inputStream = new ObjectInputStream(socket.getInputStream());

	             	Log.d("GameScreen", "Client conntected");
	             	//Start to chat
	             	Message m = new Message();
	                m.what = MSG_START;
	                myUpdateHandler.sendMessage(m);
	            	
	            } catch (IOException e) {
	                    e.printStackTrace();
	                    finish();
	            }
	        }
	    }
		
		//Thread pour lire 
		class CommunicationRead implements Runnable {
			public void run()
			{
				while (socket!=null)
				{
					if (objectTreat)
					{
						try {
							receiveObject = (SendObject) inputStream.readObject();
							objectTreat = false;
							Log.d("Receive", receiveObject.getType());
							Log.d("Receive", receiveObject.getObject().toString());
							if(receiveObject.getType().equals(TEXT))
							{
								Log.d("Receive", "Message");
								Message m = new Message();
				                m.what = MSG_EDIT_TEXT;
				                myUpdateHandler.sendMessage(m);
							}
							else if(receiveObject.getType().equals(LOCATION)) 
							{
								Log.d("Receive", "Location");
								Message m = new Message();
				                m.what = MSG_LOCATION;
				                myUpdateHandler.sendMessage(m);
							}
							else if(receiveObject.getType().equals(PHOTO)) 
							{
								Log.d("Receive", "Photo");
								Message m = new Message();
				                m.what = MSG_PHOTO;
				                myUpdateHandler.sendMessage(m);
							}
							else if(receiveObject.getType().equals(SOUND))
							{
								Log.d("Receive", "Sound");
								Message m = new Message();
				                m.what = MSG_SOUND;
				                myUpdateHandler.sendMessage(m);
							}
							else if(receiveObject.getType().equals(USER))
							{
								Log.d("Receive", "UserName");
								Message m = new Message();
				                m.what = MSG_USER;
				                myUpdateHandler.sendMessage(m);
							}
							else if (receiveObject.getType().equals(CLOSE))
							{
								Log.d("Receive", "Close");
								Message m = new Message();
				                m.what = MSG_CLOSE;
				                myUpdateHandler.sendMessage(m);
							}
							else if (receiveObject.getType().equals(LOCATION_STATUS))
							{
								Log.d("Receive", "Location Status");
								Message m = new Message();
				                m.what = MSG_LOCATION_STATUS;
				                myUpdateHandler.sendMessage(m);
							}
							
						} catch (OptionalDataException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
		
		//Thread pour ecrire
		class CommunicationWrite implements Runnable {
			public void run()
			{
				while (socket!=null)
				{
					if (readySend)
					{
						try{
							Log.d("Send", sendObject.getType());
							Log.d("Send", sendObject.getObject().toString());
		    				outputStream.writeObject(sendObject);
		    				outputStream.reset();
		
		    			}catch(IOException e)
		    			{
		    				e.printStackTrace();
		    			}
						readySend = false;
					}
					else if (readySendLocation)
					{
						try{
							Log.d("Send", sendObjectLocation.getType());
							Log.d("Send", sendObjectLocation.getObject().toString());
		    				outputStream.writeObject(sendObjectLocation);
		    				outputStream.reset();
		
		    			}catch(IOException e)
		    			{
		    				e.printStackTrace();
		    			}
						readySendLocation = false;
					}
				}
			}
		}

		@Override
		protected boolean isRouteDisplayed() {
			// TODO Auto-generated method stub
			return false;
		}
		
		//Lorsque la localisation change
	    public void onLocationChanged(Location location) { 
	      Log.d("Map", "onLocationChanged with location " + location.toString());
	      String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", location.getLatitude(), 
	                    location.getLongitude(), location.getAltitude(), location.getBearing());
	      
		    int latitude = (int)(location.getLatitude() * 1000000);
			int longitude = (int)(location.getLongitude() * 1000000);
		
			geoPoint[0] = latitude;
			geoPoint[1] = longitude;
				
			//add les elements dans sendObject
			sendObjectLocation.setType(LOCATION);
			sendObjectLocation.setObject(geoPoint);
			readySendLocation = true;
	    }


		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			
		}


		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			
		}


		@Override
		public void onStatusChanged(String provider, int status,
				Bundle extras) {
			// TODO Auto-generated method stub
			
		}
		
		//Pour jouer le audio
		public void playAudio()
		{
			 mPlayer = new MediaPlayer();
			 mPlayer.setOnCompletionListener(new OnCompletionListener() {
					
				@Override
				public void onCompletion(MediaPlayer mp) {
					// TODO Auto-generated method stub
					 playStopImageButton.setImageResource(R.drawable.play);
				}
			});
             try {
                 mPlayer.setDataSource(mFileNameReceive);
                 mPlayer.prepare();
                 mPlayer.start();
             } catch (IOException e) {
                 Log.e("Sound", "prepare() failed");
             }
             playStopImageButton.setImageResource(R.drawable.stop);
		}
		//Pour arreter le audio
		public void stopAudio()
		{
			mPlayer.release();
	        mPlayer = null;
	        playStopImageButton.setImageResource(R.drawable.play);
		}
		
		//Enable la localisation
		public void enableLocation()
		{
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER , 60000, 10, this); 
			locationButton.setText("Disable Location");
			sendObjectLocation.setType(LOCATION_STATUS);
			sendObjectLocation.setObject(ON);
			readySendLocation = true;
		}
		
		//Disable la localisation
		public void disableLocation()
		{
			locationButton.setText("Enable Location");
			locationManager.removeUpdates(this); 
			sendObjectLocation.setType(LOCATION_STATUS);
			sendObjectLocation.setObject(OFF);
			readySendLocation = true;
		}
}
